package com.cehome.cloudbox.listener;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.cehome.cloudbox.constans.ExtensionTaskProperties;
import com.cehome.cloudbox.service.IProcCommonService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;

/**
 * 全局的任务完成监听
 * @author zfl
 */
@Component
@Slf4j
public class GlobalTaskCompletedListener extends AbstractFlowableEngineEventListener {

    @Resource
    protected RepositoryService repositoryService;
    @Resource
    private IProcCommonService iProcCommonService;

    @Override
    protected void taskCompleted(FlowableEngineEntityEvent event) {
        // 得到任务实例
        FlowableEntityEventImpl eventImpl = (FlowableEntityEventImpl) event;
        TaskEntity taskEntity = (TaskEntity) eventImpl.getEntity();
        log.info("任务完成开始，taskId：{}", taskEntity.getId());
        // 获取节点信息
        BpmnModel bpmnModel = repositoryService.getBpmnModel(event.getProcessDefinitionId());
        FlowElement flowElement = bpmnModel.getFlowElement(taskEntity.getTaskDefinitionKey());

        // 抄送人数据
        String taskCcData = flowElement.getAttributeValue(ExtensionTaskProperties.NAMESPACE_URI, ExtensionTaskProperties.TASK_CC_DATA);

        // 获取申请人
        String applyUserId = Convert.toStr(taskEntity.getVariable(ExtensionTaskProperties.FLOWABLE_APPLY_USER_ID));

        // 获取抄送人IDList
        List<String> userIdList = iProcCommonService.getUserIdList(taskCcData, applyUserId);
        log.info("抄送人用户ID：{}", userIdList);
        // 设置抄送人
        if (ObjectUtil.isNotEmpty(userIdList)) {
            // 调用Service 发送消息
        }
    }

}
